#include "../../server.hpp"

void HandleClose(Channel *pchannel){
    // std::cout << "close: " << pchannel->Fd() << std::endl;
    DEBUG_LOG("Close %d", pchannel->Fd());
    pchannel->Remove();
    delete pchannel;
}

void HandleRead(Channel *pchannel){
    int fd = pchannel->Fd();
    char buf[1024] = {0};
    int ret = ::recv(fd, buf, 1023, 0);
    if(ret < 0) { 
        return HandleClose(pchannel);   
    }
    // std::cout << buf << std::endl;
    DEBUG_LOG("Read %s", buf);

    pchannel->EnableWrite();    //收到消息就可以回复消息了,启动写,写到peer
}
void HandleWrite(Channel *pchannel){
    int fd = pchannel->Fd();
    char *msg = "hello";
    int ret = send(fd, msg, strlen(msg), 0);
    if(ret < 0){
        return HandleClose(pchannel);
    }
    pchannel->DisableWrite();
}

void HandleError(Channel *pchannel){
    return HandleClose(pchannel);
}
void HandleEvent(EventLoop *loop, Channel *pchannel, uint64_t timerid){
    // std::cout << pchannel->Fd() << " event ready" << std::endl;
    loop->TimerRefresh(timerid);
}

void DeadLine(){

}

void Acceptor(EventLoop *loop, Channel *lis_channel){
    int fd = lis_channel->Fd();
    int newfd = ::accept(fd, nullptr, nullptr);
    DEBUG_LOG("accepted: %d", newfd);
    if(newfd < 0) return;

    uint64_t timerid = rand() % 100000;
    Channel *pchannel = new Channel(loop, newfd);
    pchannel->SetReadCallback(std::bind(HandleRead, pchannel));
    pchannel->SetWriteCallback(std::bind(HandleWrite, pchannel));
    pchannel->SetErrorCallback(std::bind(HandleError, pchannel));
    pchannel->SetCloseCallback(std::bind(HandleClose, pchannel));
    pchannel->SetEventCallback(std::bind(HandleEvent, loop, pchannel, timerid));
    // 期望任意事件触发都refresh一下timer
    loop->TimerAdd(timerid, 10, std::bind(HandleClose, pchannel));
    pchannel->EnableRead();
    
}

int main(){
    srand(time(nullptr));
    EventLoop loop;
    Socket lis_sock;
    bool ret = lis_sock.CreateServer(8500);

    Channel channel(&loop, lis_sock.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));
    channel.EnableRead();
    while(true){
        loop.Start();
        sleep(1);
    }
    lis_sock.Close();
    return 0;
}